package org.jeecg.modules.wlhy.bill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ExcelUtil;
import org.jeecg.modules.third.jg.report.information.service.ReportInformationService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.entity.ImportShippingBillDTO;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.DataMaskingUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: hy_shipping_note_bill
 * @Author: jeecg-boot
 * @Date:   2021-01-20
 * @Version: V1.0
 */
@Api(tags="hy_shipping_note_bill")
@RestController
@RequestMapping("/bill/hyShippingNoteBill")
@Slf4j
public class HyShippingNoteBillController extends JeecgController<HyShippingNoteBill, IHyShippingNoteBillService> {
	@Autowired
	private IHyShippingNoteBillService hyShippingNoteBillService;

	@Autowired
	private ReportInformationService reportInformationService;

	@Autowired
	private UserUtil userUtil;

	@Resource
	private IHySettingService settingService;


	/**
	 * 分页列表查询
	 *
	 * @param hyShippingNoteBill
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="hy_shipping_note_bill-分页列表查询", notes="hy_shipping_note_bill-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyShippingNoteBill hyShippingNoteBill,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyShippingNoteBill> queryWrapper = QueryGenerator.initQueryWrapper(hyShippingNoteBill, req.getParameterMap());
		String hdst = req.getParameter("hdst");
		if("1".equals(hdst)){
			queryWrapper.isNotNull("bank_hd");
		}else if("2".equals(hdst)){
			queryWrapper.isNull("bank_hd");
		}

		Page<HyShippingNoteBill> page = new Page<HyShippingNoteBill>(pageNo, pageSize);
		IPage<HyShippingNoteBill> pageList = hyShippingNoteBillService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@ApiOperation(value="hy_shipping_note_bill-分页列表查询", notes="hy_shipping_note_bill-分页列表查询")
	@GetMapping(value = "/newlist")
	public Result<?> queryList(HyShippingNoteBill hyShippingNoteBill,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<HyShippingNoteBill> queryWrapper = new QueryWrapper();

		if(userUtil.isSys()){
			if(StringUtils.isNotEmpty(hyShippingNoteBill.getCustomerId())){
				queryWrapper.eq("shipping.customer_id",hyShippingNoteBill.getCustomerId());
			}
		} else if (userUtil.isCustomerAdmin()) {
			queryWrapper.in("shipping.customer_id", userUtil.getCustomerAdminRelationIdList());
		} else {
			HyCustomer customer = userUtil.getCustomer();
			if(customer ==null){
				throw new JeecgBootException("货主信息不存在!");
			}
			queryWrapper.eq("shipping.customer_id",customer.getId());
		}
		String hdst = req.getParameter("hdst");
		if("1".equals(hdst)){
			queryWrapper.isNotNull("bill.bank_hd");
		}else if("2".equals(hdst)){
			queryWrapper.isNull("bill.bank_hd");
		}

		String payDtBegin = req.getParameter("payDt_begin");
		String payDtEnd = req.getParameter("payDt_end");

		if(StringUtils.isNotEmpty(payDtBegin)){
			queryWrapper.ge("bill.pay_dt",payDtBegin + " 00:00:00");
		}
		if(StringUtils.isNotEmpty(payDtEnd )){
			queryWrapper.le("bill.pay_dt",payDtEnd + " 23:59:59");
		}

		setQueryWrapper(hyShippingNoteBill, queryWrapper);

		queryWrapper.orderByDesc("bill.create_time");

		Page<HyShippingNoteBill> page = new Page<HyShippingNoteBill>(pageNo, pageSize);
		IPage<HyShippingNoteBill> pageList = hyShippingNoteBillService.getPageList(page, queryWrapper);
		//如果开启系统脱敏
		String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
		if("1".equals(dataMaskingFlag)) {
			for (HyShippingNoteBill dto : pageList.getRecords()) {
				dto.setBillNum(DataMaskingUtil.bankNumberMasking(dto.getBillNum()));
				dto.setActualCarrierId(DataMaskingUtil.idcardMasking(dto.getActualCarrierId()));
				dto.setDbaccno(DataMaskingUtil.bankNumberMasking(dto.getDbaccno()));
			}
		}
		return Result.OK(pageList);
	}
	private void setQueryWrapper(HyShippingNoteBill hyShippingNoteBill,QueryWrapper<HyShippingNoteBill> queryWrapper){

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getRespSource())){
			queryWrapper.eq("bill.resp_source",hyShippingNoteBill.getRespSource());
		}

		String billType = hyShippingNoteBill.getBillType();
		if(StringUtils.isNotEmpty(billType)){
			if(billType.contains(",")) {
				queryWrapper.in("bill.bill_type", Arrays.asList(billType.split(",")));
			}else {
				queryWrapper.eq("bill.bill_type", billType);
			}
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getPayChannel())){
			queryWrapper.eq("bill.pay_channel",hyShippingNoteBill.getPayChannel());
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getCompanyId())){
			queryWrapper.eq("bill.company_id",hyShippingNoteBill.getCompanyId());
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getBillNum())){
			queryWrapper.like("bill.bill_num",hyShippingNoteBill.getBillNum());
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getShippingNoteNumber())){
			queryWrapper.like("bill.shipping_note_number",hyShippingNoteBill.getShippingNoteNumber());
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getCarrier())){
			queryWrapper.like("bill.carrier",hyShippingNoteBill.getCarrier());
		}
		if(StringUtils.isNotEmpty(hyShippingNoteBill.getVehicleNumber())){
			queryWrapper.like("bill.vehicle_number",hyShippingNoteBill.getVehicleNumber());
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getDbaccno())){
			queryWrapper.like("bill.dbaccno",hyShippingNoteBill.getDbaccno());
		}
		if(StringUtils.isNotEmpty(hyShippingNoteBill.getDbaccname())){
			queryWrapper.like("bill.dbaccname",hyShippingNoteBill.getDbaccname());
		}
		if(StringUtils.isNotEmpty(hyShippingNoteBill.getCraccno())){
			queryWrapper.like("bill.craccno",hyShippingNoteBill.getCraccno());
		}
		if(StringUtils.isNotEmpty(hyShippingNoteBill.getCrlogaccno())){
			queryWrapper.like("bill.crlogaccno",hyShippingNoteBill.getCrlogaccno());
		}
		if(StringUtils.isNotEmpty(hyShippingNoteBill.getCraccname())){
			queryWrapper.like("bill.craccname",hyShippingNoteBill.getCraccname());
		}

		if(StringUtils.isNotEmpty(hyShippingNoteBill.getCarrierId())){
			queryWrapper.eq("bill.carrier_id",hyShippingNoteBill.getCarrierId());
		}

	}


//	/**
//	 *   添加
//	 *
//	 * @param hyShippingNoteBill
//	 * @return
//	 */
//	@AutoLog(value = "hy_shipping_note_bill-添加")
//	@ApiOperation(value="hy_shipping_note_bill-添加", notes="hy_shipping_note_bill-添加")
//	@PostMapping(value = "/add")
//	public Result<?> add(@RequestBody HyShippingNoteBill hyShippingNoteBill) {
//		hyShippingNoteBillService.save(hyShippingNoteBill);
//		return Result.OK("添加成功！");
//	}
//
//	/**
//	 *  编辑
//	 *
//	 * @param hyShippingNoteBill
//	 * @return
//	 */
//	@AutoLog(value = "hy_shipping_note_bill-编辑")
//	@ApiOperation(value="hy_shipping_note_bill-编辑", notes="hy_shipping_note_bill-编辑")
//	@PutMapping(value = "/edit")
//	public Result<?> edit(@RequestBody HyShippingNoteBill hyShippingNoteBill) {
//		hyShippingNoteBillService.updateById(hyShippingNoteBill);
//		return Result.OK("编辑成功!");
//	}
//
//	/**
//	 *   通过id删除
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_shipping_note_bill-通过id删除")
//	@ApiOperation(value="hy_shipping_note_bill-通过id删除", notes="hy_shipping_note_bill-通过id删除")
//	@DeleteMapping(value = "/delete")
//	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//		hyShippingNoteBillService.removeById(id);
//		return Result.OK("删除成功!");
//	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "hy_shipping_note_bill-批量删除")
//	@ApiOperation(value="hy_shipping_note_bill-批量删除", notes="hy_shipping_note_bill-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyShippingNoteBillService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}
//
//	/**
//	 * 通过id查询
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_shipping_note_bill-通过id查询")
//	@ApiOperation(value="hy_shipping_note_bill-通过id查询", notes="hy_shipping_note_bill-通过id查询")
//	@GetMapping(value = "/queryById")
//	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
//		HyShippingNoteBill hyShippingNoteBill = hyShippingNoteBillService.getById(id);
//		if(hyShippingNoteBill==null) {
//			return Result.error("未找到对应数据");
//		}
//		return Result.OK(hyShippingNoteBill);
//	}
//
    /**
    * 导出excel
    *
    * @param request
    * @param hyShippingNoteBill
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HyShippingNoteBill hyShippingNoteBill) {

		QueryWrapper<HyShippingNoteBill> queryWrapper = new QueryWrapper();

		if (userUtil.isSys()) {
			if(StringUtils.isNotEmpty(hyShippingNoteBill.getCustomerId())){
				queryWrapper.eq("shipping.customer_id",hyShippingNoteBill.getCustomerId());
			}
		} else {
			HyCustomer customer = userUtil.getCustomer();
			if (customer ==null) {
				throw new JeecgBootException("货主信息不存在!");
			}
			queryWrapper.eq("shipping.customer_id",customer.getId());
		}

		String hdst = request.getParameter("hdst");
		if ("1".equals(hdst)) {
			queryWrapper.isNotNull("bill.bank_hd");
		} else if("2".equals(hdst)) {
			queryWrapper.isNull("bill.bank_hd");
		}

		String payDtBegin = request.getParameter("payDt_begin");
		String payDtEnd = request.getParameter("payDt_end");

		if(StringUtils.isNotEmpty(payDtBegin)){
			queryWrapper.ge("bill.pay_dt",payDtBegin + " 00:00:00");
		}
		if(StringUtils.isNotEmpty(payDtEnd )){
			queryWrapper.le("bill.pay_dt",payDtEnd + " 23:59:59");
		}

		String selections = request.getParameter("selections");
		if (StringUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("bill.id", selectionList);
		}

		setQueryWrapper(hyShippingNoteBill, queryWrapper);

		queryWrapper.orderByDesc("bill.create_time");

		List<HyShippingNoteBill> list = hyShippingNoteBillService.getList(queryWrapper);

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String title = "流水单";
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, title);
		mv.addObject(NormalExcelConstants.CLASS, HyShippingNoteBill.class);

//		//按选择列导出
//		//log.info("数据-> {}", JSONUtil.toJsonStr(list));
//		String selCols = request.getParameter("selCols");
//		log.info("选择列导出运单-> cols {}", selCols);
//		if ("1".equals(selCols)) {
//			String field = request.getParameter("field");
//			log.info("选择列导出运单-> field {}", field);
//			if (StringUtils.isNotEmpty(field)) {
//				List<String> fields = Arrays.asList(field.split(","));
//				List<String> selectCols = new ArrayList<>();
//				for (String s : fields) {
//					if (StringUtils.isNotEmpty(s)) {
//						int idx = s.indexOf("_dictText");
//						if (idx > -1) {
//							s = s.substring(0, idx);
//						}
//						selectCols.add(s);
//					}
//				}
//
//				mv.addObject(NormalExcelConstants.EXPORT_FIELDS, StringUtils.join(selectCols, ","));
//			}
//		}
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
		mv.addObject(NormalExcelConstants.DATA_LIST, list);
		return mv;

        //return super.exportXls(request, hyShippingNoteBill, HyShippingNoteBill.class, "hy_shipping_note_bill");
    }
//
//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyShippingNoteBill.class);
//    }


	 @AutoLog(value = "天津运单资金流水单上报")
	 @ApiOperation(value="天津运单资金流水单上报", notes="天津运单资金流水单上报")
	 @PutMapping(value = "/upload")
	 public Result<?> upload(@RequestBody HyShippingNoteBill shippingNoteBill) {
		 return reportInformationService.uploadCapitalFlow(shippingNoteBill.getShippingId()).getCode().equals("00000") ? Result.OK("上报成功!") : Result.error("上报失败!") ;

	 }
	 @GetMapping("/getShippingNoteBill")
	 @ApiOperation(value="获取运单信息", notes="获取运单信息")
	 public Result<?> getShippingNoteBill(@RequestParam(name="id",required=true) String id) {
		 return Result.ok(hyShippingNoteBillService.getById(id));
	 }


	/**
	 * 通过excel导入数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/importShippingNoteBill", method = RequestMethod.POST)
	@RequiresPermissions("shippingbill:importExcel")
	public Result<?> importExcelShippingNote(HttpServletRequest request) {
		List<ImportShippingBillDTO> list = ExcelUtil.importExcel(request, ImportShippingBillDTO.class);

		if(CollectionUtils.isEmpty(list)) {
			throw new JeecgBootException("导入数据不能为空！");
		}

		this.checkData(list);

		List <ImportShippingBillDTO> tempListShippingNote = hyShippingNoteBillService.queryImportShippingBillDTOS(list);

		List<HyShippingNoteBill> shippingNoteBills = new ArrayList<>();
		for (int j = 0; j < tempListShippingNote.size(); j++) {
			ImportShippingBillDTO importShippingBillDTO = tempListShippingNote.get(j);
			int key =  j +2;
			HyShippingNoteBill shippingNoteBill =
					hyShippingNoteBillService.ImportShippingBillDTOTOHyShippingNoteBill(importShippingBillDTO,String.valueOf(key) ) ;
			shippingNoteBills.add(shippingNoteBill);
		}

		hyShippingNoteBillService.saveBatchShippingNote(shippingNoteBills);
		return Result.ok("文件导入成功！数据行数：" + shippingNoteBills.size());
	}

	public  void checkData(List<ImportShippingBillDTO> list  ) {
		int i=2;
		for(ImportShippingBillDTO importShippingBillDTO :list){
			String key = String.valueOf(i);
			if (importShippingBillDTO == null) {
				throw new JeecgBootException("数据对象为空");
			}
			if(StringUtils.isBlank(importShippingBillDTO.getCompanyName())){
				throw new JeecgBootException("第"+ key+ "行  公司信息不能为空,请先补充信息");
			}
			if(StringUtils.isBlank(importShippingBillDTO.getShippingNoteNumber())){
				throw new JeecgBootException("第"+ key+ "行  运单信息不能为空,请先补充信息");
			}


			if(StringUtils.isBlank(importShippingBillDTO.getCarrier())){
				throw new JeecgBootException("第"+ key+ "行 司机名称不能为空,请先补充信息");
			}
			if(StringUtils.isBlank(importShippingBillDTO.getActualCarrierId())){
				throw new JeecgBootException("第"+ key+ "行 司机身份证不能为空");
			}
			if(StringUtils.isBlank(importShippingBillDTO.getVehicleNumber())){
				throw new JeecgBootException("第"+ key+ "行  车辆号码信息不能为空,请先补充信息");
			}
			if(StringUtils.isBlank(importShippingBillDTO.getVehicleColorCode())){
				throw new JeecgBootException("第"+ key+ "行车辆颜色信息不能为空");
			}

			if( importShippingBillDTO.getAmt() == null ||
					importShippingBillDTO.getAmt().compareTo(BigDecimal.ZERO)==0 ){
				throw new JeecgBootException("第"+ key+ "行金额不能为空");
			}

			if(StringUtils.isBlank(importShippingBillDTO.getCraccno())){
				throw new JeecgBootException("第"+ key+ "行司机银行卡号不能为空");
			}
			if(StringUtils.isBlank(importShippingBillDTO.getBankCode())){
				throw new JeecgBootException("第"+ key+ "行收款方银行代码不能为空");
			}

			if(StringUtils.isBlank(importShippingBillDTO.getCreateTime())){
				throw new JeecgBootException("第"+ key+ "行创建时间不能为空");
			}
			Date createTime = DateUtils.stringToDateTime(importShippingBillDTO.getCreateTime());
			if(createTime == null){
				throw new JeecgBootException("第"+ key+ "行创建时间不正确,应为日期时间文本格式");
			}
			i++;
		}



	}

}
